package api

import (
	"context"
	"fmt"
	"log"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	global "github.com/smash-llj/Nexa-server/global"
	"github.com/smash-llj/Nexa-server/models/request"
	service "github.com/smash-llj/Nexa-server/service"
	utils "github.com/smash-llj/Nexa-server/utils"
	"github.com/spf13/viper"
)

type UserApi struct {
	BaseApi
	Service *service.UserService
}

func NewUserApi() UserApi {
	return UserApi{
		BaseApi: NewBaseApi(),
		Service: service.NewUserService(),
	}
}

func NextLoginToken(user utils.TokenUser) (string, error) {
	token, err := utils.GenerateToken(user)
	if err != nil {
		log.Fatal("token创建失败")
		return "", err
	}
	prefix := viper.GetString("Redis.PreFix") + strconv.Itoa(int(user.Id))
	_ = global.Redis.Set(context.Background(), prefix, token, time.Hour*24)
	return token, nil
}

func (u UserApi) Login(C *gin.Context) {
	var loginReq request.UserLoginReq
	if err := u.BindData(BuildBaseApiOptions{C: C, Dto: &loginReq}); err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	//校验验证码
	if ok, err := VerifyCaptcha(loginReq.CaptchaId, loginReq.CaptchaVal); !ok && err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	//用户登录逻辑
	user, err := u.Service.Login(loginReq)
	if err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	//生成token
	token, _ := NextLoginToken(utils.TokenUser{
		Name: user.Username,
		Id:   user.Id,
	})
	u.Success(Response{
		Msg: gin.H{
			"user":  user,
			"token": token,
		},
	})
}

func (u UserApi) Register(C *gin.Context) {
	var userReq request.UserRegisterReq
	if err := u.BindData(BuildBaseApiOptions{C: C, Dto: &userReq}); err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	//校验验证码
	if ok, err := VerifyCaptcha(userReq.CaptchaId, userReq.CaptchaVal); !ok && err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	if err := u.Service.Register(userReq); err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	u.Success(Response{
		Msg: "注册成功",
	})
}

func (u UserApi) UpdateUserInfo(C *gin.Context) {
	var updateReq request.UpdateUserInfoReq
	UId := utils.GetUserId(C)
	fmt.Println(UId, "当前用户")
	if err := u.BindData(BuildBaseApiOptions{C: C, Dto: &updateReq}); err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	if err := u.Service.UpdateUserInfo(UId, updateReq); err != nil {
		u.Fail(Response{Msg: err.Error()})
		return
	}
	u.Success(Response{
		Data: "更新成功",
	})
}
